<template>
  <j-modal :title="title" :width="width" :visible="visible" :confirmLoading="confirmLoading" :maskClosable="false"
    :keyboard="false" :forceRender="true" v-bind:prefixNo="prefixNo" switchHelp switchFullscreen @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp" :id="prefixNo" style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{ $t('inPrint.cancel') }}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleOk" :disabled="submitBtnDisabled">{{ $t('commodityManagement.preservation') }}</a-button>
    </template>
    <div style="position:absolute;bottom:53px;right:0;z-index:11" v-if="showRecover && !model.id">
      <span>{{ $t('popup.recoveryPrompt') }}</span>
      <a-button type="link" @click="recover" :disabled="submitBtnDisabled">{{$t('popup.recover')}}</a-button>
      <a-button type="link" @click="lose" :disabled="submitBtnDisabled">{{$t('popup.lose')}}</a-button>
    </div>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
         
          <!-- 客户 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('manuManagement.supplier')"
              data-step="1" :data-title="$t('manuManagement.supplier')"
              :data-intro="$t('popup.supplierMustBeSelectedIt')">
              <a-select :placeholder="$t('manuManagement.selectSupplier')"
                v-decorator="['organId', validatorRules.organId]" :dropdownMatchSelectWidth="false" showSearch
                allowClear
                optionFilterProp="children">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;" @mousedown="e => e.preventDefault()"
                    @click="addSupplier"><a-icon type="plus" /> {{ $t('popup.newSupplier') }}</div>
                </div>
                <a-select-option v-for="(item, index) in supList" :key="index" :value="item.id">
                  {{ item.supplier }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>


          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('popup.relatedOrder')" data-step="3"
              :data-title="$t('popup.relatedOrder')" :data-intro="$t('popup.purchaseReceiptAfterOrder')">
              <a-input-search :placeholder="$t('popup.pleaseSelectAssociated')" v-decorator="['number',validatorRules.number]"
                @search="onSearchLinkNumber" :readOnly="true" />
            </a-form-item>
          </a-col>
          
          <!-- 验收仓库 交付对象-->
          <!-- <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
              :label="$t('purchasingManagement.acceptanceWarehouse')">
              <a-select :placeholder="$t('purchasingManagement.selectAcceptanceWarehouse')"
              allowClear
                v-decorator="['checkDepotId', validatorRules.checkDepotId]">
                <a-select-option v-for="(item, index) in warehouseList" :key="index" :value="item.id">
                  {{ item.depotName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->
          
          <!-- 操作员 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')"
              data-step="3" :data-title="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator.trim="['userName']" disabled
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('purchasingManagement.settledStatementNumber')"
              data-step="3" :data-title="$t('purchasingManagement.settledStatementNumber')">
              <a-input :placeholder="$t('purchasingManagement.settledStatementNumber')" v-decorator.trim="['custom1']" disabled
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <!-- 税号 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
              :label="$t('purchasingManagement.dutyParagraph')">
              <a-input :placeholder="$t('purchasingManagement.pleaseEnterDutyParagraph')" v-decorator="['custom2']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <!-- 单据编号 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')"
              data-step="2" :data-title="$t('setailManagement.documentNo')"
              :data-intro="$t('popup.theNumberIsGenerated')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="['billNo',validatorRules.billNo]" disabled
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <!-- <a-col :lg="6" :md="12" :sm="24">
            <a-form-item v-if="purchaseBySaleFlag" :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('purchasingManagement.associatedOrder')" data-step="3" :data-title="$t('purchasingManagement.associatedOrder')"
                         :data-intro="$t('popup.purchaseOrderDocumentsSelect')">
              <a-input-search :placeholder="$t('popup.pleaseSelectAnAssociatedAales')" v-decorator="[ 'linkNumber', validatorRules.linkNumber ]" @search="onSearchLinkNumber" :readOnly="true"/>
            </a-form-item>
          </a-col> -->
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator.trim="['creator']" />
            </a-form-item>
          </a-col>
          <!-- 单据日期 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['billTime', validatorRules.billTime]" :show-time="true" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }" >
              <span>{{$t('popup.documentRemark')}}：</span>
              <a-textarea :rows="1" :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="['remark']"
                style="margin-top:8px;width: 88%;" />
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table id="billModal" :ref="refKeys[0]" :loading="materialTable.loading"
          :columns="materialTable.columns" :dataSource="materialTable.dataSource" :minWidth="minWidth" :maxHeight="300"
          :rowNumber="false" :rowSelection="rowCanEdit" :actionButton="rowCanEdit" :dragSort="false"
          @added="onAdded" @deleted="onDeleted" @valueChange="barCodeValueChange"
          @inputPurchaseValueChange="onValueChange">
          <template #buttonAfter>
            <a-row v-if="rowCanEdit" :gutter="24" style="float:left;padding-bottom: 5px;" data-step="4"
              :data-title="$t('popup.codeScanningEntry')" :data-intro="$t('popup.thisSupportsGun')">
              <a-col v-if="scanStatus" :md="6" :sm="24">
                <a-button @click="scanEnter">{{ $t('popup.codeScanningEntry') }}</a-button>
              </a-col>
              <a-col v-if="!scanStatus" :md="16" :sm="24" style="padding: 0 6px 0 12px">
                <a-input :placeholder="$t('popup.pleaseScanBarcode')" v-model="scanBarCode" @pressEnter="scanPressEnter"
                  ref="scanBarCode" />
              </a-col>
              <a-col v-if="!scanStatus" :md="6" :sm="24" style="padding: 0px">
                <a-button @click="stopScan">{{ $t('popup.stowScanningCode') }}</a-button>
              </a-col>
            </a-row>
            <a-row :gutter="24" style="float:left;padding-bottom: 5px;">
              <a-col :md="24" :sm="24">
                <a-button style="margin-left: 8px" @click="handleHistoryBillList"><a-icon type="history" />{{
                    $t('popup.historicalDocuments')
                }}</a-button>
              </a-col>
            </a-row>
          </template>
          <template #delete="record">
            <div style="text-align: center;">
              <a-popconfirm :title="$t('manuManagement.areDelete')"
                @confirm="() => removeRows(record)">
                <a-icon type="delete"></a-icon>
              </a-popconfirm>
            </div>
          </template>
          <template #rowIndex="record">
            <div style="text-align: center;">{{ record.index + 1 }}</div>
          </template>
        </j-editable-table>
        <a-row class="form-row" :gutter="24">
          <!-- <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.preferentialRate')" data-step="5" :data-title="$t('inPrint.preferentialRate')"
                         :data-intro="$t('popup.proportionDiscount')">
              <a-input style="width:185px;" :placeholder="$t('popup.pleaseDiscountRate')" v-decorator.trim="[ 'discount' ]" suffix="%" @keyup="onKeyUpDiscount"/>
            </a-form-item>
          </a-col> -->
          <!-- 优惠金额 -->
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.paymentPreference')"
              data-step="6" :data-title="$t('inPrint.paymentPreference')" :data-intro="$t('popup.theAmountGoods')">
              <a-input :placeholder="$t('popup.pleasePaymentPreference')" v-decorator.trim="['discountMoney']"
                @keyup="onKeyUpDiscountMoney" />
            </a-form-item>
          </a-col>
          <!-- 总金额 -->
          <a-col :lg="6" :md="12" :sm="24">
           <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('reportQuery.totalPrice')" data-step="7"
              :data-title="$t('inPrint.amountAfter')" :data-intro="$t('popup.amountAmountGoodsIn')">
              <a-input :placeholder="$t('popup.pleaseEnterAfterDiscount')" v-decorator.trim="['totalPrice']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24"></a-col>
        </a-row>
        <!-- 实付金额 -->
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('manuManagement.payDeposit')">
              <a-input :placeholder="$t('popup.pleaseEnterPaymentDeposit')"
                v-decorator.trim="['changeAmount']" @keyup="onKeyUpChangeAmount" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('manuManagement.payDeposit')">
              <a-input :placeholder="$t('popup.pleaseEnterPaymentDeposit')"
                v-decorator.trim="['type']" />
            </a-form-item>
          </a-col>
<!--          <a-col :lg="6" :md="12" :sm="24">
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
          </a-col> -->
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.enclosure')" data-step="10"
              :data-title="$t('inPrint.enclosure')" :data-intro="$t('popup.youUploadPictures')">
              <j-upload :fileList="fileList" bizPath="bill" :key="model.uploadKey || 1"></j-upload>

            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <many-account-modal ref="manyAccountModalForm" @ok="manyAccountModalFormOk"></many-account-modal>
    <vendor-modal ref="vendorModalForm" @ok="vendorModalFormOk"></vendor-modal>
    <account-modal ref="accountModalForm" @ok="accountModalFormOk"></account-modal>
    <link-bill-list ref="linkBillList" @ok="linkBillListOk"></link-bill-list>
    <history-bill-list ref="historyBillListModalForm"></history-bill-list>
  </j-modal>
</template>
<script>
import pick from 'lodash.pick'
import ManyAccountModal from '@/views/bill/dialog/ManyAccountModal'
import LinkBillList from '@/views/bill/dialog/LinkBillList'
import VendorModal from '@/views/system/modules/VendorModal'
import AccountModal from '@/views/system/modules/AccountModal'
import HistoryBillList from '@/views/bill/dialog/HistoryBillList'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { BillModalMixin } from '@/views/bill/mixins/BillModalMixin'
import { getCurrentSystemConfig, getAllList, gettTransportAllList, getAccount } from '@/api/api'
import { getMpListShort, changeListFmtMinus, handleIntroJs,getNowFormatDateTime } from "@/utils/util"
import JUpload from '@/components/jeecg/JUpload'
import JDate from '@/components/jeecg/JDate'
import Vue from 'vue'
export default {
  name: "FactoryFreightBillModal",
  provide(){
    return {
      getConfig: ()=>{
        return {organId : this.form.getFieldValue('organId')}
      }
    }
  },
  mixins: [JEditableTableMixin, BillModalMixin],
  components: {
    ManyAccountModal,
    LinkBillList,
    VendorModal,
    AccountModal,
    HistoryBillList,
    JUpload,
    JDate,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    }
  },
  data() {
    return {
      title: this.$t('setailManagement.operation'),
      width: '1600px',
      moreStatus: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      visible: false,
      supList: [],
      addressList: [],
      depotList: [],
      operTimeStr: '',
      prefixNo: 'ZFYF',
      fileList: [],
      rowCanEdit: true,
      purchaseBySaleFlag: true,
      submitBtnDisabled:false,//是否禁用提交按钮
      companyFax: '',
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      refKeys: ['materialDataTable'],
      tableKeys: ['materialDataTable',],
      activeKey: 'materialDataTable',
      materialTable: {
        loading: false,
        dataSource: [],
        columns: [
          { title: this.$t('commodityManagement.delete'), width: '3%', key: 'delete', type: 'slot' },
          { title: this.$t('defaultTranslate.lineNumber'), key: 'rowIndex', width: '4%', type: 'slot' },
          { title: this.$t('purchasingManagement.TransportCompany'),key: 'transpotName', width: '7%', type: FormTypes.select,options: [], placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
          { title: this.$t('purchasingManagement.transportNo'),key: 'transpotNo', width: '7%', type: FormTypes.input,options: [], placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
          // { title: this.$t('purchasingManagement.size'),key: 'packSize', width: '7%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
          { title: this.$t('purchasingManagement.size'),key: 'custom3', width: '7%', type: FormTypes.hidden, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
          // { title: 'GTIN',key: 'gtin', width: '7%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
          // { title: 'UOM',key: 'uom', width: '7%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
          { title: this.$t('purchasingManagement.size'),key: 'packsOrdered', width: '7%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
          // { title: this.$t('purchasingManagement.size'),key: 'packsSupplied', width: '7%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
          { title: this.$t('purchasingManagement.unitPrice'),key: 'unitPrice', width: '7%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
          { title: this.$t('purchasingManagement.amount'),key: 'amount', width: '7%',statistics: true, type: FormTypes.inputNumber,readonly: true, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
          { title: this.$t('purchasingManagement.discountamount'),key: 'discountAmount', statistics: true, width: '7%', type: FormTypes.inputNumber, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
          { title: this.$t('purchasingManagement.eachAmount'),key: 'eachAmount',statistics: true, width: '7%', type: FormTypes.inputNumber,readonly: true, placeholder: ''},
          { title: this.$t('purchasingManagement.IsPayByFactory'),key: 'paymentType', width: '7%', type: FormTypes.select,options: [], placeholder: this.$t('inPrint.pleaseTnter')+'${title}'}, 

        ]
      },
      confirmLoading: false,
      validatorRules: {
        billTime: {
          rules: [
            { required: true, message: this.$t('popup.pleaseEnterDocumentDate') + '!' }
          ]
        },
        organId: {
          rules: [
            { required: true, message: this.$t('popup.pleaseSupplier') + '!' }
          ]
        },
        addressId: {
          rules: [
            { required: true, message: this.$t('popup.pleaseAddress') + '!' }
          ]
        },
        checkDepotId: {
          rules: [
            { required: true, message: this.$t('purchasingManagement.importAcceptanceWarehouse') + '!' }
          ]
        },
          billNo:{
            rules: [
              { required: true, message: this.$t('otherJS.DocumentNoFailure') }
            ]
          },
          number:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectAssociated') }
            ]
          }
      },
      url: {
        add: '/accountHead/addAccountHeadAndDetail',
        edit: '/accountHead/updateAccountHeadAndDetail',
        detailList: '/accountItem/getDetailList'
      }
    }
  },
  methods: {
    // 子tableonchange事件重写，没变更都会计算总金额
    onValueChange(event){
      console.log(event,9999);
      const { type, row, column, value, target } = event
      this.submitBtnDisabled = true;
      switch (column.key) {
        case 'packsOrdered':
        target.setValues([
          {
            rowKey: row.id,
            values: {
              amount: (+row.packsOrdered *(+row.unitPrice)).toFixed(2),
              discountAmount: (+row.discountAmount).toFixed(2),
              eachAmount:((+row.packsOrdered *(+row.unitPrice)).toFixed(2) -(+row.discountAmount)).toFixed(2)
            }
          }
        ])
        break;
        case 'unitPrice':
        target.setValues([
          {
            rowKey: row.id,
            values: {
              amount: (+row.packsOrdered *(+row.unitPrice)).toFixed(2),
              discountAmount: (+row.discountAmount).toFixed(2),
              eachAmount:((+row.packsOrdered *(+row.unitPrice)).toFixed(2) -(+row.discountAmount)).toFixed(2)
            }
          }
        ])
                break;
        case 'discountAmount':
        target.setValues([
          {
            rowKey: row.id,
            values: {
              amount: (+row.packsOrdered *(+row.unitPrice)).toFixed(2),
              eachAmount:((+row.packsOrdered *(+row.unitPrice)).toFixed(2) -(+row.discountAmount)).toFixed(2)
            }
          }
        ])
        break;
        case 'transpotName':
        // 匹配no
        let transpotItem = this.transportList.find(v=>v.transpotNo === value)
        console.log(transpotItem,666);
        if(!transpotItem) break;
        target.setValues([
          {
            rowKey: row.id,
            values: {
              transpotNo:transpotItem.transpotNo || '',
              custom3:transpotItem.id || '',
            }
          }
        ])
        break;
      }

      // 触发后重新计算总金额
      this.countDiscountLastMoney();
      this.$refs.materialDataTable.recalcAllStatisticsColumns()
    },
    // 计算优惠后总金额
    countDiscountLastMoney(){
      this.$refs.materialDataTable.getValues((e,v)=>{
        let arr = v 
        let totalPrice = 0
        arr.forEach(val=>{
          totalPrice  = totalPrice +(+val.packsOrdered * (+val.unitPrice) - (+val.discountAmount))
        })
        console.log(totalPrice,666);
        // totalPrice - discountMoney = changeAmount
        this.$nextTick(() => {
          this.form.setFieldsValue({
            'totalPrice': totalPrice.toFixed(2),
            'changeAmount': totalPrice.toFixed(2)
          })
        })
      })
      this.submitBtnDisabled = false;
    },
    // 计算优惠后总金额
    countDiscountLastMoneyDefault(arr){
      let totalPrice = 0
        arr.forEach(val=>{
          totalPrice  = totalPrice +(+val.packsOrdered * (+val.unitPrice) - (+val.discountAmount))
        })
        console.log(totalPrice,666);
        // totalPrice - discountMoney = changeAmount
        this.$nextTick(() => {
          this.form.setFieldsValue({
            'totalPrice': totalPrice.toFixed(2),
            'changeAmount': totalPrice.toFixed(2)
          })
        })
      this.submitBtnDisabled = false;
    },
    // 关联订单搜索框回调
    linkBillListOk (selectBillDetailRows, linkNumber, organId, checkDepotId) {
      this.$nextTick(() => {
        this.form.setFieldsValue({
          'number': linkNumber,
          'organId': organId,
          'custom1':selectBillDetailRows[0].number,
          'checkDepotId': selectBillDetailRows[0].checkDepotId,
        })
      })
    },
    // 关联订单搜索框绑定
    onSearchLinkNumber() {
      let organId = this.form.getFieldValue('organId')
      this.$refs.linkBillList.acceptanceShow('其它', '下达采购', this.$t('manuManagement.customer'), "2", organId,this.prefixNo)
      this.$refs.linkBillList.title = this.$t('popup.selectPurchaseOrder')
    },
    // 获取产品列表
    gettTransportAllList(){
      gettTransportAllList().then(res=>{
        this.transportList = (res.data || []).filter(v=>v.transpotName && v.transpotNo)
      })
    },
    //调用完edit()方法之后会自动调用此方法
    editAfter() {
      this.arrList = []
      this.billStatus = '0'
      this.rowCanEdit = true
      this.materialTable.columns[3].type = FormTypes.popupJsh
      this.materialTable.columns[6].type = FormTypes.input
      this.getSystemConfig()
      this.changeColumnHide()
      this.changeFormTypes(this.materialTable.columns, 'transpotNo', 1)
      // this.changeFormTypes(this.materialTable.columns, 'amount', 1)
      // this.changeFormTypes(this.materialTable.columns, 'eachAmount', 1)
      if (this.action === 'add') {
        this.addInit(this.prefixNo)
        this.fileList = []
        this.$nextTick(() => {
          handleIntroJs(this.prefixNo, 1)
          this.$nextTick(() => {
            this.form.setFieldsValue({
              billTime: getNowFormatDateTime(),
            })
          })
        })
      } else {
        if (this.model.linkNumber) {
          this.rowCanEdit = false
          this.materialTable.columns[3].type = FormTypes.normal
        }
        // this.model.billTime = this.model.operTimeStr
        
        console.log('编辑数据：',this.model);
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'organId', 'deliveryMethod','billNo','custom1',
            'arrivalTime', 'billTime', 'number', 'userName', 'creator', 'custom2','freightStatus','quotationStatus','checkDepotId', 'linkNumber', 'remark',
            'discount', 'discountMoney', 'discountLastMoney', 'changeAmount'))
        });
        // 加载子表数据
        let params = {
          headerId: this.model.id,
          mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
        }
        let url = this.readOnly ? this.url.detailList : this.url.detailList;
        this.requestSubTableData(url, params, this.materialTable,()=>{
          console.log('this.materialTable :>> ', this.materialTable);
          this.$nextTick(()=>{
            this.countDiscountLastMoneyDefault(this.materialTable.dataSource)

          })
        });
        let arr = []
        this.materialTable.dataSource.forEach(item => {
          arr.push(item.materialId)
        });
        this.materialIds = arr.toString()
        this.changeMaterialIds()
        
      }
      //复制新增单据-初始化单号和日期
      if (this.action === 'copyAdd') {
        this.model.id = ''
        this.model.tenantId = ''
        this.copyAddInit(this.prefixNo)
      }
      this.initWarehouseList();
      this.initSupplier();
      this.initAddressList();
      this.initAccount();
      this.initTransport();
      this.initIsPayByFactory();
      setTimeout(() => {
        this.title = this.$t('purchasingManagement.FreightList')+ '-' + this.$t('setailManagement.newlyAdded')
      }, 0);
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let totalPrice = 0
      let billMain = Object.assign(this.model, allValues.formValue)
      let detailArr = allValues.tablesValue[0].values
      let paidFreightFee = 0
      billMain.type = '直发运费'
      billMain.subType = '下达采购'
      billMain.defaultNumber = billMain.number
      for (let item of detailArr) {
        item.depotId = '' //订单不需要仓库
        totalPrice += item.eachAmount - 0
        item.isExchange = 0
        if (item.paymentType == 1) {
          paidFreightFee += Number(item.eachAmount)
        } else if (item.paymentType === undefined) {
          item.paymentType = 0
        }
      }
      billMain.totalPrice = 0 - totalPrice
      
      billMain.changeAmount = -paidFreightFee
      if (billMain.accountId === 0) {
        billMain.accountId = ''
      }
      // this.accountMoneyList = changeListFmtMinus(this.accountMoneyList)
      // billMain.accountIdList = this.accountIdList.length > 0 ? JSON.stringify(this.accountIdList) : ""
      // billMain.accountMoneyList = this.accountMoneyList.length > 0 ? JSON.stringify(this.accountMoneyList) : ""
      if (this.fileList && this.fileList.length > 0) {
        billMain.fileName = this.fileList
      } else {
        billMain.fileName = ''
      }
      if (this.model.id) {
        billMain.id = this.model.id
      }
      billMain.status = this.billStatus
      let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
      return {
        info: JSON.stringify(billMain),
        attachment: fileList,
        rows: JSON.stringify(detailArr),
      }
    },
    handleHistoryBillList() {
      let organId = this.form.getFieldValue('organId')
      this.$refs.historyBillListModalForm.show(this.$t('manuManagement.other'), this.$t('manuManagement.purchaseOrder'), this.$t('manuManagement.supplier'), organId);
      this.$refs.historyBillListModalForm.disableSubmit = false;
    },
    // 获取系统配置
    getSystemConfig() {
      getCurrentSystemConfig().then((res) => {
        // console.log("系统配置",res.data);
        if (res.code === 200 && res.data) {
          this.purchaseBySaleFlag = res.data.purchaseBySaleFlag === '1' ? true : false
          this.form.setFieldsValue({
            'custom2': res.data.companyFax,
          })
        }
      })
    },
    removeRows (text) {
      this.$refs[this.refKeys[0]].removeRows(text.rowId)
    }
  }
}
</script>
<style scoped lang="less">
::v-deep .ant-spin-container .thead {
  background: #beddf9;
  & > .tr > .td {
    border-left: 1px solid #f2f2f2;
    text-align: center;
  }
}
</style>